#include "webplib.h"
#include "webp/decode.h"
#include "webp/encode.h"
#include "webp/decode_vp8.h"
#include "webp/buffer.h"

#ifdef _DEBUG
#pragma comment( lib, "libwebp_a_debug.lib" )
#else
#pragma comment( lib, "libwebp_a.lib" )
#endif

#ifdef _COMPILING_DLL_

namespace webp
{
	//////////////////////////////////////////////////////////////////////////
	//
	// Returns the size of the compressed data (pointed to by *output), or 0
	void LIBSPEC encode( buffer & buf, unsigned char const * input, int width, int height, color_type out_format, float quality_factor
		, AllocFunc allocator, DeallocFunc deallocator )
	{
		size_t size=0;

		buf = buffer( width, height, out_format, allocator, deallocator );

		switch( out_format )
		{
		case color_type::rgb :
			size = WebPEncodeRGB( input, width, height, width * 3, quality_factor, &buf.data() );
			break;

		case color_type::bgr :
			size = WebPEncodeBGR( input, width, height, width * 3, quality_factor, &buf.data() );
			break;

		case color_type::rgba :
			size = WebPEncodeRGBA( input, width, height, width * 4, quality_factor, &buf.data() );	
			break;

		case color_type::bgra :
			size = WebPEncodeBGRA( input, width, height, width * 4, quality_factor, &buf.data() );
			break;
		}

		buf.size() = size;
	}

	//////////////////////////////////////////////////////////////////////////
	//
	// Returns the size of the compressed data (pointed to by *output), or 0
	void LIBSPEC decode( buffer & buf, unsigned char const * input, unsigned int size, color_type out_format, int & out_width, int & out_height
		, AllocFunc allocator, DeallocFunc deallocator )
	{
		unsigned char *output = 0;

		out_width = 0;
		out_height = 0;

		if( !WebPGetInfo( input, size, &out_width, &out_height ) )
			buf = buffer( 0, 0, out_format, allocator, deallocator );

		buf = buffer( out_width, out_height, out_format, allocator, deallocator );

		switch( out_format )
		{
		case color_type::rgb :
			WebPDecodeRGBInto( input, size, buf.data(), buf.size(), out_width * 3 );
			break;

		case color_type::bgr :
			WebPDecodeBGRInto( input, size, buf.data(), buf.size(), out_width * 3 );
			break;

		case color_type::rgba :
			WebPDecodeRGBAInto( input, size, buf.data(), buf.size(), out_width * 4 );
			break;

		case color_type::bgra :
			WebPDecodeBGRAInto( input, size, buf.data(), buf.size(), out_width * 4 );
			break;
		}
	}
	//////////////////////////////////////////////////////////////////////////
}

#endif